package com.wanli.storemobile.homepage;


import android.app.Dialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.ethanhua.skeleton.Skeleton;
import com.ethanhua.skeleton.SkeletonScreen;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;
import com.wanli.storemobile.R;
import com.wanli.storemobile.base.BaseActivity;
import com.wanli.storemobile.base.DataCallBack;
import com.wanli.storemobile.bean.BaseResponseBean;
import com.wanli.storemobile.bean.DeviceListBean;
import com.wanli.storemobile.dialog.CollectCodeDialog;
import com.wanli.storemobile.dialog.KdbCodeDialog;
import com.wanli.storemobile.homepage.adapter.DeviceListAdapter;
import com.wanli.storemobile.homepage.model.HomePageModelImpl;
import com.wanli.storemobile.homepage.model.IHomePageModel;
import com.wanli.storemobile.utils.ToastUtil;
import com.wanli.storemobile.widget.AppTitleBar;
import com.yanzhenjie.permission.Action;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.runtime.Permission;
import com.yzq.zxinglibrary.android.CaptureActivity;
import com.yzq.zxinglibrary.common.Constant;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class DeviceListActivity extends BaseActivity implements OnRefreshLoadMoreListener {

    @BindView(R.id.title_bar)
    AppTitleBar titleBar;
    @BindView(R.id.ll_no_data)
    LinearLayout llNoData;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.tv_device_name)
    TextView tvDeviceName;
    @BindView(R.id.ll_device_type)
    LinearLayout llDeviceType;
    @BindView(R.id.tv_commit)
    TextView tvCommit;
    private IHomePageModel homePageModel;
    private List<DeviceListBean.DataBean.ItemListBean> beanList;
    private DeviceListAdapter listAdapter;
    private int page = 1;
    private SkeletonScreen skeletonScreen;
    private String type = "";
    private ArrayList<String> optionsItems = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_device_list);
        ButterKnife.bind(this);
        initView();
        initData();
    }

    private void initView() {
        refreshLayout.setRefreshHeader(new ClassicsHeader(mActivity));//设置Header
        refreshLayout.setRefreshFooter(new ClassicsFooter(mActivity));//设置Footer
        refreshLayout.setOnRefreshLoadMoreListener(this);

        // 1  3  4  5   6
        optionsItems.add("扫码盒");
        optionsItems.add("码牌");
        optionsItems.add("云音响");
        optionsItems.add("NFC标签卡");
        optionsItems.add("码牌音响");

        homePageModel = new HomePageModelImpl();
        beanList = new ArrayList<>();
    }

    private void initData() {
        listAdapter = new DeviceListAdapter(beanList);
        recyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
        recyclerView.setAdapter(listAdapter);

        skeletonScreen = Skeleton.bind(recyclerView)
                .adapter(listAdapter)
                .color(R.color.shimmer_color_2)
                .shimmer(true)
                .angle(20)
                .frozen(false)
                .duration(1000)
                .count(20)
                .load(R.layout.item_skeleton_device_list)
                .show();
        listAdapter.setOnCallBackListener((type, position) -> {
            DeviceListBean.DataBean.ItemListBean itemListBean = beanList.get(position);
            if (1 == type && itemListBean.getType() == 8) {
                CollectCodeDialog dialog = CollectCodeDialog.newInstance(itemListBean.getQrurl(), itemListBean.getNo());
                dialog.show(getSupportFragmentManager(), "dialog");
            }
            if (1 == type && (itemListBean.getType() == 3 || itemListBean.getType() == 6)) {
                KdbCodeDialog dialog = KdbCodeDialog.newInstance(itemListBean.getQrurl(), itemListBean.getNo());
                dialog.show(getSupportFragmentManager(), "dialog");
            }
        });
        requestData();
    }

    public void requestData() {
        homePageModel.requestDeviceUnifyIndex(page, type, new DataCallBack<DeviceListBean>() {
            @Override
            public void onSuccessful(DeviceListBean bean) {
                if (bean.getData().getItemList() != null && bean.getData().getItemList().size() > 0) {
                    beanList.addAll(bean.getData().getItemList());
                    if (page == 1) {
                        refreshLayout.finishRefresh();
                    } else {
                        refreshLayout.finishLoadMore();
                    }
                } else {
                    if (page != 1) {
                        refreshLayout.finishLoadMoreWithNoMoreData();
                    } else {
                        refreshLayout.finishRefresh();
                    }
                }
                if (beanList.size() > 0) {
                    llNoData.setVisibility(View.GONE);
                } else {
                    llNoData.setVisibility(View.VISIBLE);
                }
                listAdapter.notifyDataSetChanged();
                if (page == 1) {
                    skeletonScreen.hide();
                }
            }

            @Override
            public void onFailed(String msg, String code) {
                if (page == 1) {
                    skeletonScreen.hide();
                }
            }
        });
    }

    @Override
    public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
        page++;
        requestData();
        refreshLayout.finishLoadMore(1000);
    }

    @Override
    public void onRefresh(@NonNull RefreshLayout refreshLayout) {
        refreshData();
    }

    public void refreshData() {
        page = 1;
        beanList.clear();
        requestData();
        refreshLayout.finishRefresh(1000);
    }

    private void showGsInfo() {// 弹出选择器

        OptionsPickerView pvOptions = new OptionsPickerBuilder(mActivity, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                if (options1 == 0) {
                    type = "1";
                } else if (options1 == 1) {
                    type = "3";
                } else if (options1 == 2) {
                    type = "4";
                } else if (options1 == 3) {
                    type = "5";
                } else if (options1 == 4) {
                    type = "6";
                }
                tvDeviceName.setText(optionsItems.get(options1));
                refreshData();
            }
        }).setTitleText("")
                .setTitleSize(16)
                .setSubmitColor(getResources().getColor(R.color.text_color_2))//确定按钮文字颜色
                .setSubCalSize(14)
                .setCancelColor(getResources().getColor(R.color.text_color_2))//取消按钮文字颜色
                .setTitleBgColor(getResources().getColor(R.color.white))
                .setDividerColor(getResources().getColor(R.color.line_color_gray))
                .setTextColorCenter(getResources().getColor(R.color.text_color_2))
                .setContentTextSize(15)
                .setLineSpacingMultiplier(2)
                .isDialog(true)
                .build();


        pvOptions.setPicker(optionsItems);

        String deviceName = tvDeviceName.getText().toString();

        if ("扫码盒".equals(deviceName)) {
            pvOptions.setSelectOptions(0);
        } else if ("码牌".equals(deviceName)) {
            pvOptions.setSelectOptions(1);
        } else if ("云音响".equals(deviceName)) {
            pvOptions.setSelectOptions(2);
        } else if ("NFC标签卡".equals(deviceName)) {
            pvOptions.setSelectOptions(3);
        } else if ("码牌音响".equals(deviceName)) {
            pvOptions.setSelectOptions(4);
        }

        Dialog mDialog = pvOptions.getDialog();
        if (mDialog != null) {
            FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT,
                    Gravity.BOTTOM);

            params.leftMargin = 0;
            params.rightMargin = 0;
            pvOptions.getDialogContainerLayout().setLayoutParams(params);

            Window window = mDialog.getWindow();
            if (window != null) {
                window.setWindowAnimations(R.style.picker_view_slide_anim);//修改动画样式
                window.getDecorView().setPadding(0, 0, 0, 0);
                WindowManager.LayoutParams lp = window.getAttributes();
                lp.width = WindowManager.LayoutParams.MATCH_PARENT;
                lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
                lp.gravity = Gravity.BOTTOM;
            }
        }
        pvOptions.show();

    }

    @OnClick({R.id.ll_device_type, R.id.tv_commit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_device_type:
                showGsInfo();
                break;
            case R.id.tv_commit:
                //扫一扫
                scanCode();
                break;
        }
    }
    private int REQUEST_CODE_SCAN = 111;//扫一扫请求状态码

    public void scanCode() {
        AndPermission.with(this)
                .runtime()
                .permission(Permission.CAMERA, Permission.READ_EXTERNAL_STORAGE, Permission.WRITE_EXTERNAL_STORAGE)
                .onGranted(new Action<List<String>>() {
                    @Override
                    public void onAction(List<String> permissions) {
                        Intent intent = new Intent(DeviceListActivity.this, CaptureActivity.class);
                        startActivityForResult(intent, REQUEST_CODE_SCAN);
                    }
                })
                .onDenied(new Action<List<String>>() {
                    @Override
                    public void onAction(@NonNull List<String> permissions) {
                        Uri packageURI = Uri.parse("package:" + Objects.requireNonNull(DeviceListActivity.this).getPackageName());
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS, packageURI);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        startActivity(intent);
                        Toast.makeText(DeviceListActivity.this, "没有权限无法扫描呦", Toast.LENGTH_LONG).show();
                    }
                })
                .start();
    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // 扫描二维码/条码回传
        if (requestCode == REQUEST_CODE_SCAN && resultCode == RESULT_OK) {
            if (data != null) {
                String content = data.getStringExtra(Constant.CODED_CONTENT);
                requestqrurlBindStore(content);
            }
        }
    }

    public void requestqrurlBindStore(String qrurl) {
        homePageModel.requestqrurlBindStore(qrurl, new DataCallBack<BaseResponseBean>() {
            @Override
            public void onSuccessful(BaseResponseBean bean) {
                ToastUtil.showShort("绑定成功");
                refreshData();
            }

            @Override
            public void onFailed(String msg, String code) {

            }
        });
    }

}
